#include "gamelevel.h"

#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QString>

GameLevel::GameLevel(std::string const& _json)//解析JSON文档，用来更简便地绘制地图
{
    QJsonParseError error;
    auto json = QJsonDocument::fromJson(QString(_json.c_str()).toUtf8(), &error);//获取文档
    playerX = json.object().value("player").toArray().at(0).toInt();//建立与player条目的联系，建立x和y坐标
    playerY = json.object().value("player").toArray().at(1).toInt();

    auto dataArray = json.object().value("data").toArray();
    for(int i = 0; i < 20; ++i)
    {
        auto subDataArray = dataArray.at(i).toArray();//这是二维数组的第二维
        for(int j = 0; j < 20; ++j)
        {
            boxes[i][j] = false;
            switch(subDataArray.at(j).toInt())
            {
            case 0:
                world[i][j] = WorldTileType::EMPTY;
                break;
            case 1://数字1对应的是箱子
                world[i][j] = WorldTileType::FLOOR;
                boxes[i][j] = true;
                break;
            case 2://记号点
                world[i][j] = WorldTileType::TARGET;
                break;
            case 3://墙
                world[i][j] = WorldTileType::WALL;
                break;
            case 4://地板
                world[i][j] = WorldTileType::FLOOR;
                break;
            }
        }
    }
}

GameLevel::~GameLevel()
{

}

bool GameLevel::checkSuccess()//判断胜利的函数
{
    for(int i = 0; i < 20; ++i)
    {
        for(int j = 0; j < 20; ++j)
        {
            if(world[i][j] == WorldTileType::TARGET && !boxes[i][j])
                return false;
        }
    }
    return true;
}

void GameLevel::movePlayer(int i, int j)//制定移动箱子的规则
{
    if(!boxes[playerX + i][playerY + j] && (world[playerX + i][playerY + j] == WorldTileType::FLOOR ||
                                            world[playerX + i][playerY + j] == WorldTileType::TARGET))//如果前面是地板或者记号等可移动的情况，就移动玩家
    {
        playerX += i;
        playerY += j;
    }

    else if(boxes[playerX + i][playerY + j])
    {
        if(!boxes[playerX + i * 2][playerY + j * 2] &&
                (world[playerX + i * 2][playerY + j * 2] == WorldTileType::FLOOR ||
                 world[playerX + i * 2][playerY + j * 2] == WorldTileType::TARGET))
        {
            boxes[playerX + i][playerY + j] = false;//这里面前已有一个箱子，把这个箱子视作false，再把下一个路线视作true，就可以进行判断
            boxes[playerX + i * 2][playerY + j * 2] = true;
            playerX += i;
            playerY += j;
        }
    }
}
